<!-- 入库单修改界面 -->
<template>
    <!--基本信息-->
    <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">基础信息</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <el-form :model="instockform" :rules="rules" ref="instockref" style="margin-top: 20px;margin-left: 50px;" label-width="auto">
            <el-row>
                <el-col :span="11">
                    <el-form-item label="入库单号" prop="code">
                        <el-input placeholder="自动获取系统编号" style="width: 300px;" v-model="instockform.code" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="入库类型" prop="type">
                        <el-select placeholder="请选择" style="width: 300px;" v-model="instockform.type" disabled>
                            <el-option v-for="item in types" :key="item.bus_id" :label="item.bus_name" :value="item.bus_name"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 动态表单部分 -->
            <!-- 进货入库 -->
            <div v-if="instockform.type === '进货入库'">
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="仓库名称" prop="whid">
                            <el-select placeholder="请选择" style="width: 300px;" v-model="instockform.whid">
                                <el-option v-for="item in warehouse" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
                            </el-select>
                            <el-button type="success" text @click="setWarehouse">设置</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="入库日期" prop="date">
                            <el-date-picker v-model="instockform.date" type="datetime" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 300px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="关联单号" prop="inorder">
                            <el-input placeholder="请选择关联单号" style="width: 300px;" v-model="instockform.inorder" readonly>
                                <template #append>
                                    <el-button @click="openOrderDialog">...</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="供应商" prop="supname">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="instockform.supname" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="联系人" prop="linkman">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="instockform.linkman" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="联系方式" prop="linkphone">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="instockform.linkphone" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

            <!-- 退货入库 -->
            <div v-if="instockform.type === '退货入库'">
                 <el-row>
                    <el-col :span="11">
                        <el-form-item label="仓库名称" prop="whid">
                            <el-select placeholder="请选择" style="width: 300px;" v-model="instockform.whid">
                                <el-option v-for="item in warehouse" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
                            </el-select>
                             <el-button type="success" text @click="setWarehouse">设置</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="入库日期" prop="date">
                            <el-date-picker v-model="instockform.date" type="date" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 300px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="关联单号" prop="inorder">
                            <el-input placeholder="请选择关联单号" style="width: 300px;" v-model="instockform.inorder" readonly>
                                <template #append>
                                    <el-button @click="openOrderDialog">...</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="客户名称" prop="custname">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="instockform.custname" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="联系人" prop="linkman">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="instockform.linkman" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="联系方式" prop="linkphone">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="instockform.linkphone" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

            <!-- 调拨入库 -->
             <div v-if="instockform.type === '调拨入库'">
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="关联单号" prop="inorder">
                           <el-input placeholder="请选择关联单号" style="width: 300px;" v-model="instockform.inorder" readonly>
                                <template #append>
                                    <el-button @click="openOrderDialog">...</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="仓库名称" prop="whname">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="instockform.whname" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                     <el-col :span="11">
                        <el-form-item label="入库日期" prop="date">
                            <el-date-picker v-model="instockform.date" type="date" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 300px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

            <!-- 盘盈入库 -->
            <div v-if="instockform.type === '盘盈入库'">
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="关联单号" prop="inorder">
                            <el-input placeholder="请选择关联单号" style="width: 300px;" v-model="instockform.inorder" readonly>
                                <template #append>
                                    <el-button @click="openOrderDialog">...</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="入库日期" prop="date">
                            <el-date-picker v-model="instockform.date" type="date" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 300px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="仓库名称" prop="whname">
                            <el-input placeholder="选择关联盘点单自动带入" style="width: 300px;" v-model="instockform.whname" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

            <!-- 期初入库 -->
            <div v-if="instockform.type === '期初入库'">
                <el-row>
                   <el-col :span="11">
                        <el-form-item label="仓库名称" prop="whid">
                            <el-select placeholder="请选择" style="width: 300px;" v-model="instockform.whid">
                                <el-option v-for="item in warehouse" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
                            </el-select>
                             <el-button type="success" text @click="setWarehouse">设置</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="入库日期" prop="date">
                            <el-date-picker v-model="instockform.date" type="date" placeholder="请选择" format="YYYY-MM-DD" style="width: 300px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

            <!-- 公共字段 -->
            <el-row>
                <el-col :span="11">
                    <el-form-item label="经办人" prop="inuser">
                        <el-select placeholder="请选择" style="width: 300px;" v-model="instockform.inuser">
                            <el-option v-for="item in users" :key="item.user_id" :label="item.user_name" :value="item.user_name"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" placeholder="请输入" v-model="instockform.remark"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>

    <!-- 入库明细 -->
    <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">入库明细</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <div style="text-align: left;margin-left: 20px;">
            <el-button type="success" @click="ShowProduct">添加</el-button>
            <el-button @click="batchRemoveProducts">移除</el-button>
        </div>

        <!-- 进货入库明细 -->
        <div v-if="instockform.type === '进货入库'">
            <el-table :data="selectedProducts" stripe style="margin-top: 10px;" @selection-change="SelectChange">
                 <el-table-column fixed type="selection" width="55"></el-table-column>
                 <el-table-column fixed type="index" label="序号" width="60"></el-table-column>
                 <el-table-column fixed prop="proc_name" label="货品名称" width="120"></el-table-column>
                 <el-table-column prop="proc_code" label="货品编号" width="200"></el-table-column>
                 <el-table-column prop="type_name" label="货品类型"></el-table-column>
                 <el-table-column prop="proc_primary_unit" label="单位"></el-table-column>
                 <el-table-column prop="proc_model" label="规格型号"></el-table-column>
                 <el-table-column prop="proc_inventory" label="当前库存"></el-table-column>
                 <el-table-column prop="proc_pur_num" label="进货数量"></el-table-column>
                 <el-table-column label="已入库数量" width="120">
                    <template #default="scope">
                        {{ (scope.row.purd_instockOK_num || 0) + (scope.row.ind_num || 0) }}
                    </template>
                 </el-table-column>
                 <el-table-column label="未入库数量" width="120">
                    <template #default="scope">
                        {{ (scope.row.proc_pur_num || 0) - (scope.row.purd_instockOK_num || 0) - (scope.row.ind_num || 0) }}
                    </template>
                 </el-table-column>
                 <el-table-column label="入库库位" width="150">
                      <template #default="scope">
                         <el-select v-model="scope.row.slot_id" placeholder="请选择" style="width: 120px;">
                             <el-option v-for="loc in slots" :key="loc.slot_id" :label="loc.slot_name" :value="loc.slot_id"></el-option>
                         </el-select>
                      </template>
                 </el-table-column>
                 <el-table-column label="本次入库数量" width="200px">
                      <template #default="scope">
                         <el-input-number v-model="scope.row.ind_num" :min="1" :max="scope.row.proc_pur_num - scope.row.purd_instockOK_num"></el-input-number>
                      </template>
                 </el-table-column>
                 <el-table-column label="进货单价" prop="proc_pur_price" width="120"></el-table-column>
                 <el-table-column label="进货金额" prop="proc_pur_total" width="120"></el-table-column>
                 <el-table-column label="入库金额" prop="ind_total" width="120">
                    <template #default="scope">
                        {{ (scope.row.ind_num * scope.row.proc_pur_price || 0).toFixed(2) }}
                    </template>
                 </el-table-column>
                 <el-table-column label="生产日期" prop="proc_date" width="150">
                    <template #default="scope">
                        <el-date-picker v-model="scope.row.proc_date" type="date" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 120px;"></el-date-picker>
                    </template>
                 </el-table-column>
                 <el-table-column label="备注" prop="remark" width="150">
                    <template #default="scope">
                        <el-input v-model="scope.row.remark" placeholder="请输入" style="width: 120px;"></el-input>
                    </template>
                 </el-table-column>
                 <el-table-column label="操作" width="80" fixed="right">
                      <template #default="scope">
                          <el-button type="danger" size="small" text @click="removeProduct(scope.row.proc_id)">移除</el-button>
                      </template>
                 </el-table-column>
            </el-table>
            <div style="text-align: right; margin-top: 10px; padding: 10px 20px; border-top: 1px solid #e6e6e6;">
                 <span style="margin-right: 15px;">未入库数量: <b style="color: red;">{{ sumNotInstockNum }}</b></span>
                 <span style="margin-right: 15px;">已入库数量: <b style="color: red;">{{ sumAlreadyInstockNum }}</b></span>
                 <span style="margin-right: 15px;">入库种类: <b style="color: red;">{{ selectedProducts.length }}</b></span>
                 <span style="margin-right: 15px;">入库数量: <b style="color: red;">{{ sumInstockNum }}</b></span>
                 <span>入库金额: <b style="color: red;">{{ sumInstockAmount }}</b></span>
            </div>
        </div>

        <!-- 退货入库明细 -->
        <div v-if="instockform.type === '退货入库'">
             <el-table :data="selectedProducts" stripe style="margin-top: 10px;" @selection-change="SelectChange">
                <el-table-column fixed type="selection"></el-table-column>
                <el-table-column fixed type="index" label="序号" width="70"></el-table-column>
                <el-table-column fixed prop="proc_name" label="货品名称" width="200"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="200"></el-table-column>
                <el-table-column prop="type_name" label="货品类型" width="150"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="200"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="150"></el-table-column>
                <el-table-column prop="proc_inventory" label="当前库存" width="150"></el-table-column>
                <el-table-column prop="saletd_num" label="退货数量" width="150"></el-table-column>
                <el-table-column prop="saletd_instockOK_num" label="已入库数量" width="150"></el-table-column>
                <el-table-column prop="saletd_instockNO_num" label="未入库数量" width="150"></el-table-column>
                <el-table-column label="入库库位" width="150">
                      <template #default="scope">
                         <el-select v-model="scope.row.slot_id" placeholder="请选择" style="width: 120px;">
                             <el-option v-for="loc in slots" :key="loc.slot_id" :label="loc.slot_name" :value="loc.slot_id"></el-option>
                         </el-select>
                      </template>
                 </el-table-column>
                <el-table-column label="本次入库数量" width="200px">
                    <template #default="scope">
                        <el-input-number v-model="scope.row.ind_num" :min="1" :max="scope.row.saletd_num - scope.row.saletd_instockOK_num"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="ind_price" label="入库单价" width="200">
                    <template #default="scope">
                        <el-input-number v-model="scope.row.ind_price" :min="1"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="saletd_price" label="退货单价" width="120">
                    <template #default="scope">
                        {{ scope.row.saletd_price ? Number(scope.row.saletd_price).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="ind_total" label="入库金额" width="120"></el-table-column>
                <el-table-column label="生产日期" prop="proc_date" width="200">
                    <template #default="scope">
                        <el-date-picker v-model="scope.row.proc_date" type="date" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 120px;"></el-date-picker>
                    </template>
                 </el-table-column>
                 <el-table-column label="备注" prop="remark" width="200">
                    <template #default="scope">
                        <el-input v-model="scope.row.remark" placeholder="请输入" style="width: 120px;"></el-input>
                    </template>
                 </el-table-column>
                <el-table-column label="操作" fixed="right">
                    <template #default="scope">
                        <el-button type="danger" size="small" text @click="removeProduct(scope.row.proc_id)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: right; margin-top: 10px; padding: 10px 20px; border-top: 1px solid #e6e6e6;">
                 <span style="margin-right: 15px;">未入库数量: <b style="color: red;">{{ sumNotInstockNum }}</b></span>
                 <span style="margin-right: 15px;">已入库数量: <b style="color: red;">{{ sumAlreadyInstockNum }}</b></span>
                 <span style="margin-right: 15px;">入库种类: <b style="color: red;">{{ selectedProducts.length }}</b></span>
                 <span style="margin-right: 15px;">入库数量: <b style="color: red;">{{ sumReturnInstockNum }}</b></span>
                 <span style="margin-right: 15px;">入库金额: <b style="color: red;">{{ sumReturnInstockAmount }}</b></span>
            </div>
        </div>

        <!-- 调拨入库明细 -->
        <div v-if="instockform.type === '调拨入库'">
            <el-table :data="selectedProducts" stripe style="margin-top: 10px;" @selection-change="SelectChange">
                 <el-table-column fixed type="selection"></el-table-column>
                 <el-table-column fixed type="index" label="序号" width="70"></el-table-column>
                 <el-table-column fixed prop="proc_name" label="货品名称" width="200"></el-table-column>
                 <el-table-column prop="proc_code" label="货品编号" width="200"></el-table-column>
                 <el-table-column prop="type_name" label="货品类型" width="150"></el-table-column>
                 <el-table-column prop="proc_model" label="规格型号" width="150"></el-table-column>
                 <el-table-column prop="proc_primary_unit" label="单位" width="100"></el-table-column>
                 <el-table-column prop="proc_inventory" label="当前库存" width="150"></el-table-column>
                 <el-table-column label="入库库位" width="200">
                      <template #default="scope">
                         <el-select v-model="scope.row.slot_id" placeholder="请选择" style="width: 150px;">
                             <el-option v-for="loc in slots" :key="loc.slot_id" :label="loc.slot_name" :value="loc.slot_id"></el-option>
                         </el-select>
                      </template>
                 </el-table-column>
                 <el-table-column prop="ald_num" label="调拨数量" width="150"></el-table-column>
                 <el-table-column prop="ald_instockOK_num" label="已入库数量" width="100">
                    <template #default="scope">
                        {{ (scope.row.ald_instockOK_num || 0) + (scope.row.ind_num || 0) }}
                    </template>
                 </el-table-column>
                 <el-table-column prop="ald_instockNO_num" label="未入库数量" width="100">
                    <template #default="scope">
                        {{ (scope.row.ald_num || 0) - (scope.row.ald_instockOK_num || 0) - (scope.row.ind_num || 0) }}
                    </template>
                 </el-table-column>
                 <el-table-column label="本次入库数量" width="200">
                      <template #default="scope">
                         <el-input-number 
                            v-model="scope.row.ind_num" 
                            :min="0" 
                            :max="(scope.row.ald_num || 0) - (scope.row.ald_instockOK_num || 0)"
                            @input="handleTransferQuantityChange(scope.row)"
                            @change="handleTransferQuantityChange(scope.row)"
                            :precision="0"
                            :step="1"
                         />
                      </template>
                 </el-table-column>
                 <el-table-column prop="ald_price" label="入库单价" width="150">
                    <template #default="scope">
                         {{ (scope.row.ald_price || 0).toFixed(2) }}
                    </template>
                 </el-table-column>
                 <el-table-column prop="ind_total" label="入库金额" width="150">
                    <template #default="scope">
                        {{ ((scope.row.ind_num || 0) * (scope.row.ald_price || 0)).toFixed(2) }}
                    </template>
                 </el-table-column>
                 <el-table-column label="生产日期" prop="proc_date" width="150">
                    <template #default="scope">
                        <el-date-picker v-model="scope.row.proc_date" type="date" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 120px;"></el-date-picker>
                    </template>
                 </el-table-column>
                 <el-table-column label="备注" prop="remark" width="120">
                    <template #default="scope">
                        <el-input v-model="scope.row.remark" placeholder="请输入" style="width: 120px;"></el-input>
                    </template>
                 </el-table-column>
                 <el-table-column label="操作" fixed="right">
                      <template #default="scope">
                          <el-button type="danger" size="small" text @click="removeProduct(scope.row.proc_id)">移除</el-button>
                      </template>
                 </el-table-column>
            </el-table>
            <div style="text-align: right; margin-top: 10px; padding: 10px 20px; border-top: 1px solid #e6e6e6;">
                 <span style="margin-right: 15px;">入库种类: <b style="color: red;">{{ selectedProducts.length }}</b></span>
                 <span style="margin-right: 15px;">入库数量: <b style="color: red;">{{ sumTransferInstockNum }}</b></span>
                 <span>入库金额: <b style="color: red;">{{ sumTransferInstockAmount }}</b></span>
            </div>
        </div>

        <!-- 盘盈入库/期初入库明细 -->
        <div v-if="instockform.type === '盘盈入库' || instockform.type === '期初入库'">
            <el-table :data="selectedProducts" stripe style="margin-top: 10px;" @selection-change="SelectChange">
                <el-table-column fixed type="selection"></el-table-column>
                <el-table-column fixed type="index" label="序号" width="70"></el-table-column>
                <el-table-column fixed prop="proc_name" label="货品名称" width="150"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="150"></el-table-column>
                <el-table-column prop="type_name" label="货品类型" width="150"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="150"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位"></el-table-column>
                <el-table-column prop="proc_inventory" label="当前库存" width="150"></el-table-column>
                <el-table-column label="入库库位" width="150">
                      <template #default="scope">
                         <el-select v-model="scope.row.slot_id" placeholder="请选择" style="width: 120px;">
                             <el-option v-for="loc in slots" :key="loc.slot_id" :label="loc.slot_name" :value="loc.slot_id"></el-option>
                         </el-select>
                      </template>
                 </el-table-column>
                <el-table-column label="入库数量" width="220">
                     <template #default="scope">
                         <el-input-number 
                             v-model="scope.row.ind_num" 
                             :min="instockform.type === '盘盈入库' ? scope.row.profitandloss_num : 1"
                             :max="instockform.type === '盘盈入库' ? scope.row.profitandloss_num : undefined"
                             :placeholder="instockform.type === '盘盈入库' ? `最大${scope.row.profitandloss_num}` : '请输入数量'">
                         </el-input-number>
                     </template>
                </el-table-column>
                <el-table-column prop="instock_price" label="入库单价" width="220">
                    <template #default="scope">
                        <el-input-number 
                            v-model="scope.row.ind_price" 
                            :min="instockform.type === '盘盈入库' ? scope.row.icd_price : 1"
                            :placeholder="instockform.type === '盘盈入库' ? `参考${scope.row.icd_price}` : '请输入单价'">
                        </el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="ind_total" label="入库金额" width="150"></el-table-column>
                <el-table-column label="生产日期" prop="proc_date" width="150">
                    <template #default="scope">
                        <el-date-picker v-model="scope.row.proc_date" type="date" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 120px;"></el-date-picker>
                    </template>
                 </el-table-column>
                 <el-table-column label="备注" prop="remark" width="150">
                    <template #default="scope">
                        <el-input v-model="scope.row.remark" placeholder="请输入" style="width: 120px;"></el-input>
                    </template>
                 </el-table-column>
                <el-table-column label="操作" fixed="right">
                     <template #default="scope">
                         <el-button type="danger" size="small" text @click="removeProduct(scope.row.proc_id)">移除</el-button>
                     </template>
                </el-table-column>
            </el-table>
            <div style="text-align: right; margin-top: 10px; padding: 10px 20px; border-top: 1px solid #e6e6e6;">
                 <span style="margin-right: 15px;">入库种类: <b style="color: red;">{{ selectedProducts.length }}</b></span>
                 <span style="margin-right: 15px;">入库数量: <b style="color: red;">{{ sumSurplusInstockNum }}</b></span>
                 <span>入库金额: <b style="color: red;">{{ sumSurplusInstockAmount }}</b></span>
            </div>
        </div>
    </div>

    <!--上传附件-->
    <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">上传附件</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <el-upload
            :file-list="filelist" 
            class="upload-demo"
            action="http://localhost:5194/api/PublicFile/Uploadfile"
            multiple
            name="files"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :limit="3"
            :on-exceed="handleExceed"
            :on-success="handleFileSuccess"
            :headers="headers"
            style="text-align: left;margin-left: 20px;">
            <el-button type="primary">上传附件</el-button>
                <template #tip>
                    <div class="el-upload__tip">
                        您可以上传doc, pdf, rar等格式的文件，单个文件上传最大200MB。
                    </div>
                </template>
        </el-upload>
    </div>

    <!-- 底部操作栏 -->
    <div class="action-bar">
        <el-button @click="Close">关闭</el-button>
       <el-button @click="SaveAsDraft" :disabled="isWarehouseLocked">保存为草稿</el-button>
         <el-button type="primary" @click="OK" :disabled="isWarehouseLocked">保存</el-button>
        <span v-if="isWarehouseLocked" style="color: #F56C6C; margin-left: 15px;">
            <i class="el-icon-lock" style="margin-right: 5px;"></i>所选仓库已锁定，无法保存
        </span>
    </div>

    <!--展示货品信息模态框-->
    <el-dialog v-model="dialogTableVisible" title="添加货品" width="800" :close-on-click-modal="false">
        <!-- 动态标题和搜索 -->
        <div v-if="instockform.type === '进货入库'">
            <div style="font-weight: bold; margin-bottom: 10px;">
                进货单号: {{ instockform.inorder }} | 进货日期: {{ instockform.date }} | 供应商: {{ instockform.supname }}
            </div>
        </div>
        <div v-if="instockform.type === '退货入库'">
            <div style="font-weight: bold; margin-bottom: 10px;">
                退货单号: {{ instockform.inorder }} | 退货日期: {{ instockform.date }} | 客户: {{ instockform.custname }}
            </div>
        </div>
        <div v-if="instockform.type === '调拨入库'">
            <div style="font-weight: bold; margin-bottom: 10px;">
                调拨单号: {{ instockform.inorder }} | 仓库: {{ instockform.whname }}
            </div>
        </div>
        <div v-if="instockform.type === '盘盈入库'">
            <div style="font-weight: bold; margin-bottom: 10px;">
                盘点单号: {{ instockform.inorder }} | 盘点日期: {{ formatDisplayDate(instockform.date) }} | 仓库: {{ instockform.whname }}
            </div>
        </div>
        <div>
            <el-form :model="procform" ref="procref" :inline="true" style="text-align: left;">
                <el-form-item label="货品名称" prop="name">
                    <el-input placeholder="请输入货品名称" v-model="procform.name"></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="unit">
                    <el-select placeholder="请选择单位" v-model="procform.unit" style="width: 200px;">
                        <el-option v-for="item in units" :key="item.dict_label" :label="item.dict_label" :value="item.dict_label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="Reset">重置</el-button>
                    <el-button type="success" @click="Search">查询</el-button>
                </el-form-item>
            </el-form>
            <!--表格: 进货入库-->
            <el-table v-if="instockform.type === '进货入库'" :data="procdata" stripe height="400" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
                <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
                <el-table-column type="index" label="序号" width="70"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="150"></el-table-column>
                <el-table-column prop="proc_name" label="货品名称" width="150"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="120"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="proc_pur_price" label="进货单价" width="100">
                    <template #default="scope">
                        {{ scope.row.proc_pur_price ? Number(scope.row.proc_pur_price).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="proc_pur_num" label="进货数量" width="100"></el-table-column>
                <el-table-column prop="proc_pur_total" label="进货金额" width="100">
                    <template #default="scope">
                        {{ scope.row.proc_pur_total ? Number(scope.row.proc_pur_total).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="purd_instockOK_num" label="已入库" width="100"></el-table-column>
                <el-table-column label="未入库" width="100">
                    <template #default="scope">
                        {{ scope.row.proc_pur_num - scope.row.purd_instockOK_num }}
                    </template>
                </el-table-column>
            </el-table>

            <!--表格: 退货入库-->
            <el-table v-if="instockform.type === '退货入库'" :data="procdata" stripe height="400" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
                <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
                <el-table-column type="index" label="序号" width="70"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="200"></el-table-column>
                <el-table-column prop="proc_name" label="货品名称" width="200"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="200"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="150"></el-table-column>
                <el-table-column prop="saletd_price" label="退货单价" width="150">
                    <template #default="scope">
                        {{ scope.row.saletd_price ? Number(scope.row.saletd_price).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="saletd_num" label="退货数量" width="150"></el-table-column>
                <el-table-column prop="saletd_total" label="退货金额" width="150">
                    <template #default="scope">
                        {{ scope.row.saletd_total ? Number(scope.row.saletd_total).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="saletd_instockOK_num" label="已入库" width="150"></el-table-column>
                <el-table-column prop="saletd_instockNO_num" label="未入库" width="150"></el-table-column>
            </el-table>

            <!--表格: 调拨入库-->
            <el-table v-if="instockform.type === '调拨入库'" :data="procdata" stripe height="400" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
                <el-table-column fixed type="selection" width="50" :selectable="isSelectable"></el-table-column>
                <el-table-column fixed type="index" label="序号" width="70"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="150"></el-table-column>
                <el-table-column fixed prop="proc_name" label="货品名称" width="150"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="120"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="ald_price" label="调拨单价" width="100">
                    <template #default="scope">
                        {{ scope.row.ald_price ? Number(scope.row.ald_price).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="ald_num" label="调拨数量" width="100"></el-table-column>
                <el-table-column prop="ald_total" label="调拨金额" width="100">
                    <template #default="scope">
                        {{ scope.row.ald_total ? Number(scope.row.ald_total).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="ald_instockOK_num" label="已入库" width="100"></el-table-column>
                <el-table-column prop="ald_instockNO_num" label="未入库" width="100"></el-table-column>
            </el-table>

            <!--表格: 盘盈入库-->
            <el-table v-if="instockform.type === '盘盈入库'" :data="procdata" stripe height="400" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
                <el-table-column fixed type="selection" width="50"></el-table-column>
                <el-table-column fixed type="index" label="序号" width="70"></el-table-column>
                <el-table-column fixed prop="proc_code" label="货品编号" width="200"></el-table-column>
                <el-table-column prop="proc_name" label="货品名称" width="200"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="200"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="150"></el-table-column>
                <el-table-column prop="icd_price" label="盘点单价" width="120">
                    <template #default="scope">
                        {{ scope.row.icd_price ? Number(scope.row.icd_price).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="icd_num" label="盘点数量" width="120"></el-table-column>
                <el-table-column prop="profitandloss_num" label="盘盈数量" width="120" fixed="right">
                    <template #default="scope">
                        <span style="color: #67C23A;">{{ scope.row.profitandloss_num }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="profitandloss_total" label="盘盈金额" width="120" fixed="right">
                    <template #default="scope">
                        <span style="color: #67C23A;">{{ scope.row.profitandloss_total ? Number(scope.row.profitandloss_total).toFixed(2) : '0.00' }}</span>
                    </template>
                </el-table-column>
            </el-table>


            <!--表格: 期初入库-->
            <el-table v-if="instockform.type === '期初入库'" :data="procdata" stripe height="400" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
                 <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
                 <el-table-column type="index" label="序号" width="70"></el-table-column>
                 <el-table-column prop="proc_code" label="货品编号" width="150"></el-table-column>
                 <el-table-column prop="proc_name" label="货品名称" width="150"></el-table-column>
                 <el-table-column prop="proc_model" label="规格型号" width="120"></el-table-column>
                 <el-table-column prop="proc_primary_unit" label="单位" width="80"></el-table-column>
                 <el-table-column prop="instock_price" label="入库单价" width="100">
                     <template #default="scope">
                         {{ scope.row.instock_price ? Number(scope.row.instock_price).toFixed(2) : '0.00' }}
                     </template>
                 </el-table-column>
                 <el-table-column prop="proc_inventory" label="当前库存" width="100">
                     <template #default="scope">
                         {{ scope.row.proc_inventory || 0 }}
                     </template>
                 </el-table-column>
            </el-table>

            <div style="display: flex; justify-content: flex-end; margin-top: 15px;">
                 <!-- 页码 -->
                <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
                    v-on:current-change="handlePageChange">
                </el-pagination>
            </div>
        </div>
        <template #footer>
            <div style="text-align: right;">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="success" @click="confirmProductSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>


    <!--单据模态框-->
    <el-dialog v-model="OrderDialog" :title="orderDialogTitle" width="800" :close-on-click-modal="false">
        <!--进货单据-->
        <el-table v-if="instockform.type === '进货入库'" :data="orderData" stripe border height="400" @selection-change="selectOrder">
            <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
            <el-table-column type="index" label="序号" width="70"></el-table-column>
            <el-table-column prop="pur_code" label="进货单号" width="200"></el-table-column>
            <el-table-column prop="pur_status" label="单据状态" width="120"></el-table-column>
            <el-table-column prop="pur_date" label="进货日期" width="200"></el-table-column>
            <el-table-column prop="sup_name" label="供应商" width="150"></el-table-column>
            <el-table-column prop="pur_depName" label="进货部门" width="150"></el-table-column>
            <el-table-column prop="pur_userName" label="进货人" width="150"></el-table-column>
            <el-table-column prop="pur_num" label="货品数量" width="150"></el-table-column>
            <el-table-column prop="pur_total" label="进货金额" width="150"></el-table-column>
        </el-table>

        <!--退货单据-->
        <el-table v-if="instockform.type === '退货入库'" :data="orderData" stripe height="400" border @selection-change="selectOrder">
            <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
            <el-table-column type="index" label="序号" width="70"></el-table-column>
            <el-table-column prop="salet_code" label="退货单号" width="220"></el-table-column>
            <el-table-column prop="salet_status" label="单据状态" width="150"></el-table-column>
            <el-table-column prop="salet_date" label="退货日期" width="200"></el-table-column>
            <el-table-column prop="cust_name" label="客户名称" width="200"></el-table-column>
            <el-table-column prop="sale_userName" label="销售负责人" width="150"></el-table-column>
            <el-table-column prop="salet_num" label="货品数量" width="150"></el-table-column>
            <el-table-column prop="salet_total" label="销售金额" width="150"></el-table-column>
        </el-table>

        <!--调拨单据-->
        <el-table v-if="instockform.type === '调拨入库'" :data="orderData" stripe height="400" border @selection-change="selectOrder">
            <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
            <el-table-column type="index" label="序号" width="150"></el-table-column>
            <el-table-column prop="al_code" label="调拨单号" width="200"></el-table-column>
            <el-table-column prop="al_date" label="调拨申请日" width="200"></el-table-column>
            <el-table-column prop="al_type" label="调拨类型" width="150"></el-table-column>
            <el-table-column prop="in_wh_name" label="调入仓库" width="150"></el-table-column>
            <el-table-column prop="al_num" label="调拨数量" width="150"></el-table-column>
            <el-table-column prop="al_total" label="调拨金额" width="150">
                <template #default="scope">
                    {{ scope.row.al_total ? Number(scope.row.al_total).toFixed(2) : '0.00' }}
                </template>
            </el-table-column>
            <el-table-column prop="approver_name" label="制单人" width="150"></el-table-column>
            <el-table-column prop="approver_time" label="制单时间" width="150"></el-table-column>
        </el-table>

         <!--盘盈单据-->
         <el-table v-if="instockform.type === '盘盈入库'" :data="orderData" stripe height="400" border @selection-change="selectOrder">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column type="index" label="序号" width="70"></el-table-column>
            <el-table-column prop="ic_code" label="盘点单号" width="200"></el-table-column>
            <el-table-column prop="start_time" label="盘点开始时间" width="200"></el-table-column>
            <el-table-column prop="end_time" label="盘点结束时间" width="200"></el-table-column>
            <el-table-column prop="wh_name" label="盘点仓库" width="150"></el-table-column>
            <el-table-column prop="ic_type" label="盘点类型" width="120"></el-table-column>
            <el-table-column prop="check_num" label="盘点数量" width="120"></el-table-column>
            <el-table-column prop="checkprofit_num" label="盘盈数量" width="120">
                <template #default="scope">
                    <span style="color: #67C23A;">{{ scope.row.checkprofit_num }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="checkprofit_total" label="盘盈金额" width="120">
                <template #default="scope">
                    <span style="color: #67C23A;">{{ scope.row.checkprofit_total ? Number(scope.row.checkprofit_total).toFixed(2) : '0.00' }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="create_name" label="制单人" width="120"></el-table-column>
            <el-table-column prop="create_time" label="制单时间" width="200"></el-table-column>
        </el-table>
        <template #footer>
            <div style="text-align: right;">
                <el-button @click="OrderDialog = false">取消</el-button>
                <el-button type="success" @click="confirmOrder">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
  
<script>
import {ref,reactive,onMounted, computed, watch} from 'vue';
import http from '../auth/index';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';

export default {
    setup(){
        const router = useRouter();
        const route = useRoute();
        const user = JSON.parse(sessionStorage.getItem("user"));
        //传过来的id和code
        const instockid = route.params.instockid;
        const instockcode = route.params.instockcode;

        // 表单和校验规则
        const instockref = ref(null);
        const instockform = reactive({
            id: "",//单据id
            code: "",
            type: "",
            whid: "",
            whname: "",
            date: new Date(),
            inorder: "",
            sup: "",
            supname:"",
            cust:"",
            custname:"",
            linkman: "",
            linkphone: "",
            inuser: "",
            remark: "",
        });
        const rules = reactive({
            type: [{ required: true, message: '请选择入库类型', trigger: 'blur' }],
            whid: [{ required: true, message: '请选择仓库名称', trigger: 'blur' }],
            date: [{ required: true, message: '请选择入库日期', trigger: 'blur' }],
            inuser: [{ required: true, message: '请选择经办人', trigger: 'blur' }],
            inorder: [{ required: true, message: '请选择关联单号', trigger: 'blur' }],
        });

         //日期转换格式
         function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

         // 下拉框数据
        const types = ref([]);
        const warehouse = ref([]);
        const users = ref([]);
        const slots = ref([]); // 库位

        const isWarehouseLocked = ref(false);
        // 获取下拉框数据
        const GetTypes = () => http.get("/BusinessType/GetBusinessTypes?field=入库").then(res => types.value = res.data);
        const GetWarehouses = () => http.get("/Warehouse/GetWarehouses").then(res => {
            warehouse.value = res.data;
            // 筛选出未锁定的仓库 (is_lock=0 表示未锁定)
            const availableWarehouses = res.data.filter(wh => wh.is_lock !== 1);
            const lockedWarehouses = res.data.filter(wh => wh.is_lock === 1);
            
            // 如果有锁定仓库，为它们添加特殊标记
            if (lockedWarehouses.length > 0) {
                lockedWarehouses.forEach(wh => {
                    wh.wh_name = `${wh.wh_name} [已锁定]`;
                });
            }
            
            // 合并可用仓库和锁定仓库，但锁定仓库将有明显标记
            warehouse.value = [...availableWarehouses, ...lockedWarehouses];
        });

        const GetUsers = () => http.get("/User/GetAllUser").then(res => users.value = res.data);
        const GetSlots = (whid) => {
            if (!whid) {
                slots.value = [];
                return;
            }
            http.get(`/Slot/GetSlotsByWhid?whid=${whid}`).then(res => {
                slots.value = res.data;
            }).catch(() => {
                slots.value = [];
            });
        }
        //查询所有单据状态
        const status=ref([]);
        function GetStatus(){
            return http.get("/DictData/GetAllDictDataBytype?typeid=6")
            .then(res=>{
                status.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }
         // 状态映射计算属性
         const statusMap = computed(() => {
            const map = {};
            if (status.value && status.value.length > 0) {
                status.value.forEach(item => {
                    map[item.dict_value] = item.dict_label;
                });
            }
            return map;
        });

        
        // 计算销售总额
        const calculateAmount = (row) => {
            row.proc_sale_total = (row.proc_sale_num || 0) * (row.proc_sale_price || 0);
        };

        //#region 合计行计算
        // 合计行计算
        // 通用
        const sumNotInstockNum = computed(() => {
            const type = instockform.type;
            return selectedProducts.value.reduce((sum, item) => {
                let num = 0;
                if (type === '进货入库') num = (item.proc_pur_num || 0) - (item.purd_instockOK_num || 0) - (item.ind_num || 0);
                else if (type === '退货入库') num = (item.saletd_num || 0) - (item.saletd_instockOK_num || 0) - (item.ind_num || 0);
                else if (type === '调拨入库') num = item.ald_instockNO_num || 0;
                return sum + num;
            }, 0);
        });

        const sumAlreadyInstockNum = computed(() => {
            const type = instockform.type;
            return selectedProducts.value.reduce((sum, item) => {
                let num = 0;
                if (type === '进货入库') num = (item.purd_instockOK_num || 0) + (item.ind_num || 0);
                else if (type === '退货入库') num = (item.saletd_instockOK_num || 0) + (item.ind_num || 0);
                else if (type === '调拨入库') num = item.ald_instockOK_num || 0;
                return sum + num;
            }, 0);
        });


        // 进货
        const sumInstockNum = computed(() => selectedProducts.value.reduce((sum, item) => sum + (item.ind_num || 0), 0));
        const sumInstockAmount = computed(() => {
            const total = selectedProducts.value.reduce((sum, item) => sum + (item.ind_num || 0) * (item.proc_pur_price || 0), 0);
            return total.toFixed(2);
        });

        // 退货
        const sumReturnInstockNum = computed(() => selectedProducts.value.reduce((sum, item) => sum + (item.ind_num || 0), 0));
        const sumReturnInstockAmount = computed(() => {
            const total = selectedProducts.value.reduce((sum, item) => {
                const amount = (item.ind_num || 0) * (item.ind_price || 0);
                item.ind_total = amount.toFixed(2); // 更新行内金额
                return sum + amount;
            }, 0);
            return total.toFixed(2);
        });
        const sumReturnSaleAmount = computed(() => {
            const total = selectedProducts.value.reduce((sum, item) => {
                const amount = (item.ind_num || 0) * (item.proc_saled_price || 0);
                item.proc_saled_total = amount.toFixed(2); // 更新行内金额
                return sum + amount;
            }, 0);
            return total.toFixed(2);
        });

         // 调拨
        const sumTransferInstockNum = computed(() => 
          selectedProducts.value.reduce((sum, item) => sum + (item.ind_num || 0), 0)
        );

        const sumTransferInstockAmount = computed(() => {
          const total = selectedProducts.value.reduce((sum, item) => {
            const amount = (item.ind_num || 0) * (item.ald_price || 0);
            return sum + amount;
          }, 0);
          return total.toFixed(2);
        });

        // 盘盈、期初
        const sumSurplusInstockNum = computed(() => selectedProducts.value.reduce((sum, item) => sum + (item.ind_num || 0), 0));
        const sumSurplusInstockAmount = computed(() => {
            const total = selectedProducts.value.reduce((sum, item) => {
                const amount = (item.ind_num || 0) * (item.ind_price || 0);
                item.ind_total = amount.toFixed(2); // 更新行内金额
                return sum + amount;
            }, 0);
            return total.toFixed(2);
        });
        //#endregion


        //获取单位
        function Getunit(){
            http.get("/DictData/GetAllDictDataBytype?typeid=8")
            .then(res => units.value = res.data);
        }


        //#region 获取单据
        const OrderDialog = ref(false);
        const orderData = ref([]);

        const orderDialogTitle = computed(() => {
            const type = instockform.type;
            if (type === '进货入库') return '选择进货单';
            if (type === '退货入库') return '选择退货单';
            if (type === '调拨入库') return '选择调拨单';
            if (type === '盘盈入库') return '选择盘点单';
            return '选择单据';
        });
        
        function openOrderDialog(){
            OrderDialog.value = true;
            GetOrder();
        }
        async function GetOrder(){
            const type = instockform.type;
            if (!type) {
                ElMessage.warning("请先选择入库类型");
                return;
            }

            let url = "";

            if (type === '进货入库') {
                url = `/Purchase_h/GetAllPurchase_h`;
            } else if (type === '退货入库') {
                url = `/SaleReturn_h/GetAllSaleReturn_h`;
            } else if (type === '调拨入库') {
                url = `/Allot_h/GetAllot_Hs?name=instock_status`;
            } else if (type === '盘盈入库') {
                url = `/Check_h/Getying`;
            }

            try {
                const res = await http.get(url);
                
                if (type === '进货入库') {
                    orderData.value = res.data
                    .filter(item => item.pur_status !== 6) // 过滤条件
                    .map(item => ({
                        ...item,
                        pur_date: formatDateTime(new Date(item.pur_date)),
                        pur_total: item.pur_total.toFixed(2),
                        pur_status: statusMap.value[item.pur_status] || "未知状态"
                    }));
                } else if (type === '退货入库') {
                    orderData.value = res.data.map(item => ({
                        ...item,
                        salet_date: formatDateTime(new Date(item.salet_date)),
                        salet_total: item.salet_total.toFixed(2),
                        salet_status: statusMap.value[item.salet_status] || "未知状态"
                    }));
                } else if (type === '盘盈入库') {
                    // 处理盘点单数据
                    orderData.value = res.data.map(item => ({
                        ...item,
                        start_time: formatDateTime(new Date(item.start_time)),
                        end_time: formatDateTime(new Date(item.end_time)),
                        create_time: formatDateTime(new Date(item.create_time)),
                    }));
                }else if(type === '调拨入库'){
                    orderData.value = res.data.map(item => ({
                        ...item,
                        al_date: formatDateTime(new Date(item.al_date)),
                        approver_time: formatDateTime(new Date(item.approver_time)),
                    }));
                } else {
                    orderData.value = res.data;
                }
            } catch (error) {
                console.error("获取单据失败:", error);
                ElMessage.error("获取单据失败");
            }
        }

        //------------------
        //选中的单据
        const selectedOrders = ref([]);
        function selectOrder(val){
            selectedOrders.value = val;
        }

        async function confirmOrder(){
            if(selectedOrders.value.length === 0){
                ElMessage.warning("请先选择关联单号");
                return;
            }
            const selected = selectedOrders.value[0];
            const type = instockform.type;
            
            // 调拨入库需要检查出库状态
            if (type === '调拨入库') {
                if (selected.outstock_status !== 2) {
                    ElMessage.error("该调拨单尚未完成出库，不能进行入库操作！");
                    return;
                }
            }
            
            // 切换关联单据时，清空已选货品
            selectedProducts.value = [];
            // 如果是盘盈入库，需要检查仓库是否锁定
            if (type === '盘盈入库' && selected.wh_id) {
                try {
                    // 获取仓库信息以检查锁定状态
                    const warehouseRes = await http.get(`/Warehouse/GetIdWarehouse?id=${selected.wh_id}`);
                    if (warehouseRes.data && warehouseRes.data.is_lock === 1) {
                        ElMessage.error(`仓库 ${selected.wh_name} 已被锁定，不能用于入库操作！`);
                        isWarehouseLocked.value = true; // 设置锁定状态
                        return;
                    } else {
                        isWarehouseLocked.value = false; // 确保未锁定
                    }
                } catch (error) {
                    console.error("获取仓库状态失败:", error);
                    ElMessage.warning("无法验证仓库状态，请稍后再试");
                }
            }

            if (type === '进货入库') {
                instockform.id = selected.pur_id;
                instockform.inorder = selected.pur_code;
                instockform.sup=selected.sup_id;
                instockform.supname=selected.sup_name;
                instockform.linkman=selected.sup_linkman;
                instockform.linkphone=selected.sup_linkphone;
            } else if (type === '退货入库') {
                instockform.id = selected.salet_id;
                instockform.inorder = selected.salet_code;
                instockform.cust=selected.cust_id;
                instockform.custname=selected.cust_name;
                instockform.linkman=selected.cust_linkman;
                instockform.linkphone=selected.cust_linkphone;
            }else if (type === '盘盈入库') {
                // 为盘盈入库设置信息
                instockform.id = selected.ic_id;
                instockform.inorder = selected.ic_code;
                instockform.whid = selected.wh_id;
                instockform.whname = selected.wh_name;
            }else if(type==="调拨入库"){
                instockform.id = selected.al_id;
                instockform.inorder = selected.al_code;
                instockform.whid = selected.in_wh_id;
                instockform.whname = selected.in_wh_name;
            }
            
            OrderDialog.value = false;
        }
        //#endregion


        //#region 获取货品
        // 添加货品弹窗
        const procform = reactive({ name: "", unit: "" });
        const procref = ref(null);
        const procdata = ref([]);
        const rows = ref(0);
        const currentPage = ref(1);
        const units = ref([]);
        const dialogTableVisible = ref(false);
        function ShowProduct(){
            const type = instockform.type;
            const associatedOrderTypes = ['进货入库', '退货入库', '调拨入库', '盘盈入库'];

            // 如果是需要关联单据的类型，但尚未选择单据
            if (associatedOrderTypes.includes(type) && !instockform.inorder) {
                ElMessage.warning("请先选择关联单据后再添加货品！");
                return;
            }

            dialogTableVisible.value = true;
            All();
        }
        async function All(){
            const type = instockform.type;
            //关联单据id
            const orderId = instockform.id;

            if (!type) {
                ElMessage.warning("请先选择入库类型");
                return;
            }

            const associatedOrderTypes = ['进货入库', '退货入库', '调拨入库', '盘盈入库'];
            const isAssociatedOrder = associatedOrderTypes.includes(type);

            let url = "";
            let requestConfig = {};

            // 1. 根据入库类型，准备URL和请求参数
            if (isAssociatedOrder) {
                if (type === '进货入库') {
                    url = `/Purchase_d/GetPurchase_Ds?purid=${orderId}`;
                } else if (type === '退货入库') {
                    url = `/SaleReturn_d/GetSaleReturn_Ds?saletid=${orderId}`;
                } else if (type === '调拨入库') {
                    url = `/Allot_d/GetAllot_d?id=${orderId}`;
                } else if (type === '盘盈入库') {
                    url = `/Check_d/GetCheck_DsYingKui?icid=${orderId}&status=盘盈`;
                }
            } else { // 期初入库或其他直接选择货品的场景
                url = `/Product/GetAdvancedProduct`;
                requestConfig = {
                    params: {
                        code: "",
                        name: procform.name,
                        typeid: "",
                        model: "",
                        unit: procform.unit,
                        startinprice: "",
                        endinprice: "",
                        startoutprice: "",
                        endoutprice: "",
                        is_datamanagement: "",
                        startwarningdays: "",
                        endwarningdays: "",
                        status: "",
                        barcode: "",
                        whid: "",
                        starttime: "",
                        endtime: "",
                        createname: "",
                        CurrentPage: currentPage.value
                    }
                };
            }

            // 2. 执行数据获取和处理
            try {
                const res = await http.get(url, requestConfig);
                const initialDetails = res.data.list || res.data;

                // 2.1 如果是关联单据，执行"两步走"数据合并
                if (isAssociatedOrder) {
                    if (!initialDetails || initialDetails.length === 0) {
                        procdata.value = [];
                        rows.value = 0;
                        return ElMessage.info("此单据没有可供选择的货品。");
                    }
                    
                    const productInfoPromises = initialDetails.map(item => 
                        http.get(`/Product/GetProductById?id=${item.proc_id}`)
                    );
                    const productInfoResponses = await Promise.all(productInfoPromises);
                    const fullProductInfos = productInfoResponses.map(res => res.data);

                    const combinedProducts = initialDetails.map(orderItem => {
                        const fullProductInfo = fullProductInfos.find(p => p.proc_id === orderItem.proc_id);
                        return {
                            ...orderItem,
                            proc_code: fullProductInfo ? fullProductInfo.proc_code : 'N/A',
                            proc_model: fullProductInfo ? fullProductInfo.proc_model : 'N/A',
                            proc_primary_unit: fullProductInfo ? fullProductInfo.proc_primary_unit : 'N/A',
                            type_name: fullProductInfo ? fullProductInfo.type_name : 'N/A',
                            proc_inventory: fullProductInfo ? fullProductInfo.proc_inventory : 'N/A',
                        };
                    });

                    // 增加一个健壮的过滤步骤，确保在计算时处理 null 或 undefined 的情况
                    let filteredProducts = combinedProducts;
                    if (type === '进货入库') {
                        filteredProducts = combinedProducts.filter(p => ((p.proc_pur_num || 0) - (p.purd_instockOK_num || 0)) > 0);
                    } else if (type === '退货入库') {
                        filteredProducts = combinedProducts.filter(p => ((p.saletd_num || 0) - (p.saletd_instockOK_num || 0) - (p.ind_num || 0)) > 0);
                    } else if (type === '调拨入库') {
                        filteredProducts = combinedProducts.filter(p => (p.ald_instockNO_num || 0) > 0);
                    } 

                    procdata.value = filteredProducts;
                } else {
                // 2.2 如果是直接查询，直接赋值
                    procdata.value = initialDetails;
                    rows.value = res.data.rows || 0;
                }
            } catch (error) {
                ElMessage.error("获取货品数据失败");
                procdata.value = [];
                rows.value = 0;
            }
        }

        //改变页数
        function handlePageChange(page){
            currentPage.value = page;
            All();
        };

        //重置
        function Reset(){
            procref.value?.resetFields();
        }
        //搜索
        function Search(){
            All();
        }
        //是否可选择
        function isSelectable(row){
            return true;
        }
        //表格行样式
        function tableRowClassName(){
            return '';
        }

        //#endregion
        
        
        //#region 确认选择货品
        const multipleSelection = ref([]);
         //选中的产品
        function handleSelectionChange(selection){
            multipleSelection.value = selection;
        }

        function confirmProductSelection(){
             if (multipleSelection.value.length === 0) {
                 ElMessage.warning('请至少选择一个产品');
                 return;
             }
 
             multipleSelection.value.forEach(item => {
                 const existingIndex = selectedProducts.value.findIndex(p => p.proc_id === item.proc_id);
                 
                 if(existingIndex === -1) {
                     const newItem = {
                         ...item,
                         proc_inventory: item.proc_inventory||0,
                         proc_pur_price: (item.proc_pur_price || 0).toFixed(2),
                         proc_pur_total: (item.proc_pur_total || 0).toFixed(2),
                         proc_saled_price: (item.proc_saled_price || 0).toFixed(2),
                         proc_saled_total: (item.proc_saled_total || 0).toFixed(2),
                         proc_instock_price: (item.proc_instock_price || 0).toFixed(2),
                         proc_instock_total: (item.proc_instock_total || 0).toFixed(2),
                       };
                       selectedProducts.value.push(newItem);
                 }
             });
             dialogTableVisible.value = false;
        };

         // 明细表格
        const selectedProducts = ref([]);
        const selectdata = ref([]);
        const SelectChange = (val) => selectdata.value = val;

        //移除货品
        function removeProduct(procId) {
            const index = selectedProducts.value.findIndex(item => item.proc_id === procId);
            if (index !== -1) {
                selectedProducts.value.splice(index, 1);
            }
        };

        //批量移除货品
        function batchRemoveProducts() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请先选择要移除的货品');
                return;
            }
            selectdata.value.forEach(item => {
                const index = selectedProducts.value.findIndex(p => p.proc_id === item.proc_id);
                if (index !== -1) {
                    selectedProducts.value.splice(index, 1);
                }
            });
            ElMessage.success(`已移除${selectdata.value.length}个货品`);
        };
        //#endregion
         

        //#region 附件
        const filelist = ref([])
        //头部带token
        const token=sessionStorage.getItem('token');
        const headers = {
             Authorization: `Bearer ${token}`, // 添加 token 到请求头
        };
        // 上传成功回调方法
        function handleFileSuccess(response, file, fileList) {
            if (Array.isArray(response)) {
                // 创建 { 文件名: URL } 的映射
                const urlMap = response.reduce((map, res) => {
                    if (res.success) map[res.originalName] = res.path;
                    return map;
                }, {});
                
                // 更新文件列表
                filelist.value = fileList.map(item => ({
                    ...item,
                    url: urlMap[item.name] || item.url,  // 优先使用新URL
                    status: urlMap[item.name] ? 'success' : item.status,
                    originalName: item.originalName || item.name
                }));
            }
        }
        //预览
        function handlePreview(file){
            if (!file.url) {
                ElMessage.error('文件URL不存在，请重新上传');
                return;
            }
            const ext = file.name.split('.').pop().toLowerCase();
            
            switch (ext) {
                case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp':
                    window.open(file.url, '_blank');
                    break;
                case 'pdf':
                    window.open(file.url, '_blank');
                    break;
                case 'doc': case 'docx': case 'xls': case 'xlsx': case 'ppt': case 'pptx':
                    window.open(file.url, '_blank');
                    break;
                default:
                    // 下载其他格式文件
                    const link = document.createElement('a');
                    link.href = file.url;
                    link.download = file.name;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
            }
        };

        //移除附件
        function handleRemove(file, fileList) {
            filelist.value = fileList;
        }
        //#endregion

        // 其他按钮
        const setWarehouse = () => router.push('/main/warehouse');

        // 监视仓库ID的变化，以动态获取库位
        watch(() => instockform.whid, (newWhId) => {
            // 清空明细表中的库位选择
            selectedProducts.value.forEach(product => {
                product.slot_id = null; 
            });
            // 根据新仓库ID获取库位列表
            GetSlots(newWhId);
        });

        //根据类型和单号加载关联单据信息，以获取其ID
        async function loadAssociatedOrder(type, orderCode) {
            if (!type || !orderCode) return;

            let url = "";
            let order;

            try {
                if (type === '进货入库') {
                    url = `/Purchase_h/GetAllPurchase_h`;
                    const res = await http.get(url);
                    order = res.data.find(o => o.pur_code === orderCode);
                    if (order) {
                        instockform.id = order.pur_id; // 设置关联单据ID
                    }
                } else if (type === '退货入库') {
                    url = `/SaleReturn_h/GetAllSaleReturn_h`;
                    const res = await http.get(url);
                    order = res.data.find(o => o.salet_code === orderCode);
                    if (order) {
                        instockform.id = order.salet_id; // 设置关联单据ID
                    }
                }else if(type==='盘盈入库'){
                    url = `/Check_h/Getying`;
                    const res = await http.get(url);
                    order = res.data.find(o => o.ic_code === orderCode);
                    if (order) {
                        instockform.id = order.ic_id; // 设置关联单据ID
                    }
                }else if(type==="调拨入库"){
                    url = `/Allot_h/GetAllot_Hs?name=instock_status`;
                    const res = await http.get(url);
                    order = res.data.find(o => o.al_code === orderCode);
                    if (order) {
                        instockform.id = order.al_id; // 设置关联单据ID
                    }
                }
                
                if (!order) {
                     console.warn(`未找到关联的单据: ${orderCode}`);
                }
            } catch (error) {
                ElMessage.error(`加载关联单据'${orderCode}'失败`);
            }
        }


        //获取单据及单据明细数据
        async function getInstockData(){
            try{
                //1.获取入库单主表数据
                const h_res = await http.get(`/Instock_h/GetInstock_hById?instockid=${instockid}`);
                const data = h_res.data;
                instockform.code = data.in_code;
                instockform.type = data.in_type
                instockform.whid = data.wh_id;
                instockform.whname = data.wh_name;
                instockform.date = formatDateTime(new Date(data.in_date));
                instockform.inorder = data.in_order;
                instockform.sup = data.sup_id;
                instockform.supname = data.sup_name;
                instockform.cust = data.cust_id;
                instockform.custname = data.cust_name;
                instockform.linkman = data.linkman;
                instockform.linkphone = data.linkphone;
                instockform.inuser = data.in_user;
                instockform.remark = data.remark;

                 // 2. 根据主表信息，加载关联单据ID
                if (instockform.inorder) {
                    await loadAssociatedOrder(instockform.type, instockform.inorder);
                }

                // 3.获取入库单明细数据
                const d_res = await http.get(`/Instock_d/GetInstock_Ds?instockid=${instockid}`);
                const instockDetails = d_res.data;

                if (!instockDetails || instockDetails.length === 0) {
                    selectedProducts.value = [];
                    return;
                }

                // 4. 数据扩充：聚合货品信息和源单据（如进货单）的明细信息
                const productIds = [...new Set(instockDetails.map(item => item.proc_id))];

                // 并行获取所有货品的完整信息
                const productInfoPromises = productIds.map(id => http.get(`/Product/GetProductById?id=${id}`));
                const productInfoResponses = await Promise.all(productInfoPromises);
                const productInfoMap = new Map(productInfoResponses.map(res => res.data ? [res.data.proc_id, res.data] : null).filter(Boolean));

                // 根据入库类型，获取关联的源单据明细
                let sourceDetailsMap = new Map();
                if (instockform.type === '进货入库' && instockform.id) {
                    try {
                        const pur_d_res = await http.get(`/Purchase_d/GetPurchase_Ds?purid=${instockform.id}`);
                        if (pur_d_res.data && Array.isArray(pur_d_res.data)) {
                             sourceDetailsMap = new Map(pur_d_res.data.map(item => [item.proc_id, item]));
                        }
                    } catch (error) {
                        console.error("获取进货明细失败:", error);
                        ElMessage.warning("获取关联的进货明细失败，部分信息可能不完整。");
                    }
                }else if (instockform.type === '退货入库' && instockform.id) {
                    try {
                        const saletd_d_res = await http.get(`/SaleReturn_d/GetSaleReturn_Ds?saletid=${instockform.id}`);
                        if (saletd_d_res.data && Array.isArray(saletd_d_res.data)) {
                             sourceDetailsMap = new Map(saletd_d_res.data.map(item => [item.proc_id, item]));
                        }
                    } catch (error) {
                        console.error("获取退货明细失败:", error);
                        ElMessage.warning("获取关联的退货明细失败，部分信息可能不完整。");
                    }
                }else if(instockform.type === '盘盈入库' && instockform.id){
                    try {
                        const check_d_res = await http.get(`/Check_d/GetCheck_DsYingKui?icid=${instockform.id}&status=盘盈`);
                        if (check_d_res.data && Array.isArray(check_d_res.data)) {
                             sourceDetailsMap = new Map(check_d_res.data.map(item => [item.proc_id, item]));
                        }
                    } catch (error) {
                        console.error("获取盘盈明细失败:", error);
                        ElMessage.warning("获取关联的盘盈明细失败，部分信息可能不完整。");
                    }
                }else if(instockform.type === '调拨入库' && instockform.id){
                    try {
                        const allot_d_res = await http.get(`/Allot_d/GetAllot_d?id=${instockform.id}`);
                        if (allot_d_res.data && Array.isArray(allot_d_res.data)) {
                             sourceDetailsMap = new Map(allot_d_res.data.map(item => [item.proc_id, item]));
                        }
                    } catch (error) {
                        console.error("获取调拨明细失败:", error);
                        ElMessage.warning("获取关联的调拨明细失败，部分信息可能不完整。");
                    }
                }

                // 将入库明细、货品信息、源单据明细三方数据聚合
                const combinedDetails = instockDetails.map(item => {
                    const productInfo = productInfoMap.get(item.proc_id) || {};
                    const sourceDetail = sourceDetailsMap.get(item.proc_id) || {};
                    
                    // 聚合数据。顺序很重要：
                    // sourceDetail 提供基础信息（如进货量）
                    // productInfo 提供货品通用信息（如名称、规格）
                    // item 提供本次入库最具体的信息（如本次入库量、库位），会覆盖前两者的同名字段
                    return {
                        ...sourceDetail,
                        ...productInfo,
                        ...item,
                        proc_id: item.proc_id // 确保proc_id的正确性
                    };
                });
                
                selectedProducts.value = combinedDetails;

                //加载附件
                http.get("/PublicFile/GetPublicFileBy?type=入库单&code="+instockcode)
            .then(res=>{
                    console.log(res.data)
                    filelist.value=res.data.map(item=>{
                        return {
                            name: item.title,
                            url:item.file_name,
                            originalName:item.title
                        }
                    })
                })

            } catch(error) {
                ElMessage.error("加载入库单数据失败，请检查网络或联系管理员");
                console.error(error);
            }
        }


        //修改
        async function Update(status = 2) {
              //1.验证表单
              if (!instockref.value) return;
              const isValid = await instockref.value.validate();
              if(!isValid) return false;

             //2.验证货品
              if (selectedProducts.value.length === 0) {
                  ElMessage.warning('请添加要入库的货品！');
                  return false;
              }
              for (const product of selectedProducts.value) {
                  if (!product.slot_id) {
                      ElMessage.warning(`请为货品【${product.proc_name}】选择入库库位！`);
                      return false;
                  }
                  if (!product.ind_num || product.ind_num <= 0) {
                      ElMessage.warning(`请输入货品【${product.proc_name}】的入库数量！`);
                      return false;
                  }
              }
             
             //3.修改数据
             let instockdata = {}
             let instockdetaildata={};
             const filelistdata = filelist.value.map(item => {
                 return {
                     business_type:"入库单",
                     business_code:instockcode,
                     title: item.originalName,
                     file_name: item.url,
                 }
             })
             //--------------------------------
             if(instockform.type==='进货入库'){
                 //入库单
                 instockdata = {
                     in_id:instockid,//入库ID
                     wh_id: instockform.whid,//仓库ID
                     wh_name: warehouse.value.find(item => item.wh_id === instockform.whid)?.wh_name||'',//仓库名称
                     in_date: formatDateTime(new Date(instockform.date)),//入库日期
                     in_order: instockform.inorder||'',//关联单号
                     sup_id: instockform.sup||0,//供应商ID
                     sup_name: instockform.supname||'',//供应商名称
                     cust_id: instockform.cust||0,//客户ID
                     cust_name: instockform.custname||'',//客户名称
                     linkman: instockform.linkman||'',//联系人
                     linkphone: instockform.linkphone||'',//联系电话
                     in_user:instockform.inuser,//经办人
                     in_categories:selectedProducts.value.length,//入库种类
                     in_num:sumInstockNum.value,//入库数量
                     in_total:sumInstockAmount.value,//入库金额
                     in_instockOK_num:sumAlreadyInstockNum.value,//已入库数量
                     in_instockNO_num:sumNotInstockNum.value,//未入库数量
                     in_status: status,//单据状态
                     update_name: user.name,//更新人
                     update_time: formatDateTime(new Date()),//更新时间
                     remark: instockform.remark,//入库备注
                 }
                 //入库明细
                 instockdetaildata = selectedProducts.value.map(item => {
                     const currentInstockQty = item.ind_num || 0;
                     const originalInstockOkQty = item.purd_instockOK_num || 0;
                     return {
                         ind_id:item.ind_id,//入库明细ID
                         in_id:instockid,//入库单ID
                         proc_id: item.proc_id,
                         proc_name: item.proc_name,
                         slot_id: item.slot_id,
                         slot_name: slots.value.find(s => s.slot_id === item.slot_id)?.slot_name || '',
                         ind_price: item.proc_pur_price || 0,
                         ind_num: currentInstockQty,
                         ind_instockOK_num: originalInstockOkQty + currentInstockQty,
                         ind_instockNO_num: (item.proc_pur_num || 0) - (originalInstockOkQty + currentInstockQty),
                         ind_total: currentInstockQty * (item.proc_pur_price || 0),
                         proc_date: item.proc_date ? formatDateTime(new Date(item.proc_date)) : formatDateTime(new Date()),
                         remark: item.remark || '',
                     }
                 });
             } else if(instockform.type==='期初入库'){
                 //入库单
                 instockdata = {
                     in_id:instockid,//入库ID
                     wh_id: instockform.whid,
                     wh_name: warehouse.value.find(item => item.wh_id === instockform.whid)?.wh_name||'',
                     in_date: formatDateTime(new Date(instockform.date)),
                     in_order: instockform.inorder||'',//关联单号
                     sup_id: instockform.sup||0,//供应商ID
                     sup_name: instockform.supname||'',//供应商名称
                     cust_id: instockform.cust||0,//客户ID
                     cust_name: instockform.custname||'',//客户名称
                     linkman: instockform.linkman||'',//联系人
                     linkphone: instockform.linkphone||'',//联系电话
                     in_user:instockform.inuser,
                     in_categories:selectedProducts.value.length,
                     in_num:sumSurplusInstockNum.value,
                     in_total:sumSurplusInstockAmount.value,
                     in_instockOK_num:sumSurplusInstockNum.value,
                     in_instockNO_num:0,
                     in_status: status,//单据状态
                     update_name: user.name,
                     update_time: formatDateTime(new Date()),
                     remark: instockform.remark,
                 }
                 //入库明细
                 instockdetaildata = selectedProducts.value.map(item => {
                     const qty = item.ind_num || 0;
                     const price = item.ind_price || 0;
                     return {
                         ind_id:item.ind_id,//入库明细ID
                         in_id:instockid,//入库单ID
                         proc_id: item.proc_id,
                         proc_name: item.proc_name,
                         slot_id: item.slot_id,
                         slot_name: slots.value.find(s => s.slot_id === item.slot_id)?.slot_name || '',
                         ind_num: qty,
                         ind_price: price,
                         ind_total: qty * price,
                         proc_date: item.proc_date ? formatDateTime(new Date(item.proc_date)) : formatDateTime(new Date()),
                         remark: item.remark || '',
                     }
                 })
             }else if(instockform.type==='退货入库'){
                //入库单
                instockdata = {
                     in_id:instockid,//入库ID
                     wh_id: instockform.whid,//仓库ID
                     wh_name: warehouse.value.find(item => item.wh_id === instockform.whid)?.wh_name||'',//仓库名称
                     in_date: formatDateTime(new Date(instockform.date)),//入库日期
                     in_order: instockform.inorder||'',//关联单号
                     sup_id: instockform.sup||0,//供应商ID
                     sup_name: instockform.supname||'',//供应商名称
                     cust_id: instockform.cust||0,//客户ID
                     cust_name: instockform.custname||'',//客户名称
                     linkman: instockform.linkman||'',//联系人
                     linkphone: instockform.linkphone||'',//联系电话
                     in_user:instockform.inuser,//经办人
                     in_categories:selectedProducts.value.length,//入库种类
                     in_num:sumReturnInstockNum.value,//入库数量
                     in_total:sumReturnInstockAmount.value,//入库金额
                     in_instockOK_num:sumAlreadyInstockNum.value,//已入库数量
                     in_instockNO_num:sumNotInstockNum.value,//未入库数量
                     in_status: status,//单据状态
                     update_name: user.name,//更新人
                     update_time: formatDateTime(new Date()),//更新时间
                     remark: instockform.remark||"",//入库备注
                 }
                 //入库明细
                 instockdetaildata = selectedProducts.value.map(item => {
                     const currentInstockQty = item.ind_num || 0;
                     const originalInstockOkQty = item.saletd_instockOK_num || 0;
                     return {
                         ind_id:item.ind_id,//入库明细ID
                         in_id:instockid,//入库单ID
                         proc_id: item.proc_id,
                         proc_name: item.proc_name,
                         slot_id: item.slot_id,
                         slot_name: slots.value.find(s => s.slot_id === item.slot_id)?.slot_name || '',
                         ind_price: item.saletd_price || 0,
                         ind_num: currentInstockQty,
                         ind_instockOK_num: originalInstockOkQty + currentInstockQty,
                         ind_instockNO_num: (item.saletd_num || 0) - (originalInstockOkQty + currentInstockQty),
                         ind_total: currentInstockQty * (item.saletd_price || 0),
                         proc_date: item.proc_date ? formatDateTime(new Date(item.proc_date)) : formatDateTime(new Date()),
                         remark: item.remark || "",
                     }
                 });
             }else if(instockform.type==="盘盈入库"){
                 //入库单
                 instockdata = {
                     in_id:instockid,//入库ID
                     wh_id: instockform.whid,
                     wh_name: warehouse.value.find(item => item.wh_id === instockform.whid)?.wh_name||'',
                     in_date: formatDateTime(new Date(instockform.date)),
                     in_order: instockform.inorder||'',//关联单号
                     sup_id: instockform.sup||0,//供应商ID
                     sup_name: instockform.supname||'',//供应商名称
                     cust_id: instockform.cust||0,//客户ID
                     cust_name: instockform.custname||'',//客户名称
                     linkman: instockform.linkman||'',//联系人
                     linkphone: instockform.linkphone||'',//联系电话
                     in_user:instockform.inuser,
                     in_categories:selectedProducts.value.length,
                     in_num:sumSurplusInstockNum.value,
                     in_total:sumSurplusInstockAmount.value,
                     in_instockOK_num:sumSurplusInstockNum.value,
                     in_instockNO_num:0,
                     in_status: status,//单据状态
                     update_name: user.name,
                     update_time: formatDateTime(new Date()),
                     remark: instockform.remark,
                 }
                 //入库明细
                 instockdetaildata = selectedProducts.value.map(item => {
                     const qty = item.ind_num || 0;
                     const price = item.ind_price || 0;
                     return {
                         ind_id:item.ind_id,//入库明细ID
                         in_id:instockid,//入库单ID
                         proc_id: item.proc_id,
                         proc_name: item.proc_name,
                         slot_id: item.slot_id,
                         slot_name: slots.value.find(s => s.slot_id === item.slot_id)?.slot_name || '',
                         ind_num: qty,
                         ind_price: price,
                         ind_total: qty * price,
                         proc_date: item.proc_date ? formatDateTime(new Date(item.proc_date)) : formatDateTime(new Date()),
                         remark: item.remark || '',
                     }
                 })
             }else if(instockform.type==='调拨入库'){ 
                //入库单
                 instockdata = {
                     in_id:instockid,//入库ID
                     wh_id: instockform.whid,//仓库ID
                     wh_name: warehouse.value.find(item => item.wh_id === instockform.whid)?.wh_name||'',//仓库名称
                     in_date: formatDateTime(new Date(instockform.date)),//入库日期
                     in_order: instockform.inorder||'',//关联单号
                     sup_id: instockform.sup||0,//供应商ID
                     sup_name: instockform.supname||'',//供应商名称
                     cust_id: instockform.cust||0,//客户ID
                     cust_name: instockform.custname||'',//客户名称
                     linkman: instockform.linkman||'',//联系人
                     linkphone: instockform.linkphone||'',//联系电话
                     in_user:instockform.inuser,//经办人
                     in_categories:selectedProducts.value.length,//入库种类
                     in_num:sumTransferInstockNum.value,//入库数量
                     in_total:sumTransferInstockAmount.value,//入库金额
                     in_instockOK_num:sumTransferInstockNum.value,//已入库数量
                     in_instockNO_num:0,//未入库数量
                     in_status: status,//单据状态
                     update_name: user.name,//更新人
                     update_time: formatDateTime(new Date()),//更新时间
                     remark: instockform.remark,//入库备注
                 }
                 //入库明细
                 instockdetaildata = selectedProducts.value.map(item => {
                     const currentInstockQty = item.ind_num || 0;
                     const originalInstockOkQty = item.ald_instockOK_num || 0;
                     return {
                         ind_id:item.ind_id,//入库明细ID
                         in_id:instockid,//入库单ID
                         proc_id: item.proc_id,
                         proc_name: item.proc_name,
                         slot_id: item.slot_id,
                         slot_name: slots.value.find(s => s.slot_id === item.slot_id)?.slot_name || '',
                         ind_numtotal: item.ald_num || 0, // 调拨总数量
                         ind_price: item.instock_price || 0, // 入库单价
                         ind_num: currentInstockQty, // 本次入库数量
                         ind_instockOK_num: originalInstockOkQty + currentInstockQty, // 累计已入库数量
                         ind_instockNO_num: (item.ald_num || 0) - (originalInstockOkQty + currentInstockQty), // 剩余未入库数量
                         ind_total: currentInstockQty * (item.instock_price || 0), // 本次入库金额
                         proc_date: item.proc_date ? formatDateTime(new Date(item.proc_date)) : formatDateTime(new Date()),
                         remark: item.remark || '',
                     }
                 });
             }

             
             // 将所有数据整合到一个 payload 对象中，用于事务性提交
             let payload = {
                 instockData: instockdata,
                 instockDetails: instockdetaildata,
                 attachments: filelistdata
             };

             console.log("发往后端的完整数据包 (Payload):", payload);
             try {
                const res = await http.post("/Instock_h/UpdateInstock_h", payload);
                if (res.data > 0) {
                    ElMessage.success("更新成功");
                    return true;
                } else {
                    ElMessage.error("更新失败");
                    return false;
                }
             } catch (err) {
                 console.error("完整错误响应:", err.response?.data || err);
                 ElMessage.error("请求失败，请检查网络或联系管理员。");
                 return false;
             }
        };

        //保存为草稿
        async function SaveAsDraft() {
            const result = await Update(1); // 传入状态 1 表示草稿
            if (result) {
                router.push("../../instock");
            }
        }
        
        //保存
        async function OK() {
            const result = await Update(2); // 传入状态 2 表示待审核
            if (result) {
                router.push("../../instock");
            }
        }

        //关闭
        function Close(){
            router.back();
        }
        //挂载
        onMounted(()=>{
            getInstockData().then(() => {
                GetStatus().then(()=>{
                    GetOrder();
                });
                GetTypes();
                GetWarehouses();
                GetUsers();
                Getunit();
            });
        });

        // 添加日期显示格式化函数
        function formatDisplayDate(dateInput) {
            if (!dateInput) return '';
            
            // 如果已经是格式化的字符串，直接返回
            if (typeof dateInput === 'string') {
                // 如果是 YYYY-MM-DD HH:mm:ss 格式，提取日期部分
                if (dateInput.includes(' ')) {
                    return dateInput.split(' ')[0];
                }
                return dateInput;
            }
            
            // 如果是 Date 对象，格式化为 YYYY-MM-DD
            if (dateInput instanceof Date) {
                return dateInput.toLocaleDateString();
            }
            
            // 尝试转换为 Date 对象
            try {
                const date = new Date(dateInput);
                if (!isNaN(date.getTime())) {
                    return date.toLocaleDateString();
                }
            } catch (error) {
                console.warn('日期格式化失败:', dateInput);
            }
            
            return dateInput || '';
        }

        return {
            instockform, instockref, rules, types, warehouse, users, slots,
            selectedProducts, selectdata, SelectChange, removeProduct, batchRemoveProducts,
            sumNotInstockNum, sumAlreadyInstockNum, sumInstockNum, sumInstockAmount,
            sumReturnInstockNum, sumReturnInstockAmount, sumReturnSaleAmount,
            sumTransferInstockNum, sumTransferInstockAmount,
            sumSurplusInstockNum, sumSurplusInstockAmount,
            dialogTableVisible, ShowProduct, procform, procref, procdata, rows, currentPage,
            Reset, units, Search, handlePageChange, confirmProductSelection,
            handleSelectionChange, multipleSelection, isSelectable, tableRowClassName,
            filelist, headers, handleFileSuccess, handlePreview, handleRemove,
            Close, setWarehouse,OK,SaveAsDraft,
            calculateAmount,
            OrderDialog, openOrderDialog, orderDialogTitle,orderData,selectedOrders,selectOrder,confirmOrder,
            isWarehouseLocked,
            formatDisplayDate
        }
    }
}
</script>
  
<style scoped>
    /* 白色圆角容器 - 核心样式 */
    .white-container {
        background: white;
        border-radius: 12px;
        margin-bottom: 50px;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
        width: 75%;
    }

    /* 底部操作栏自适应 */
    .action-bar {
        position: fixed;
        bottom: 0;
        right: 0.5%; /* 与表单右侧对齐 */
        left: 210px; /* 与菜单栏宽度一致 */
        background: white;
        border-top: 1px solid #e6e6e6;
        padding: 15px;
        text-align: right;
    }

    /* 模态框样式 */
    :deep(.el-dialog__body) {
        padding: 10px 20px;
    }
    
    :deep(.el-dialog__footer) {
        border-top: 1px solid #e6e6e6;
        padding: 10px 0;
    }
    
    :deep(.el-dialog__header) {
        border-bottom: 1px solid #e6e6e6;
    }

    :deep(.el-table .warning-row) {
        background: #fef0f0 !important;
    }

    :deep(.el-table .warning-row > td) {
        background: #fef0f0 !important;
    }
</style>




